<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------


namespace app\adminapi\lists\room;


use app\adminapi\lists\BaseAdminDataLists;
use app\adminapi\service\DataHandleService;
use app\common\lists\ListsExcelInterface;
use app\common\lists\ListsSearchInterface;
use app\common\model\room\RoomHospital;
use app\common\model\room\RoomHospitalLog;
use think\facade\Db;


/**
 * 全院住户导出(季度)列表
 * Class RoomHospitalExportSeason
 * @package app\adminapi\listsroom
 */
class RoomHospitalExportSeason extends BaseAdminDataLists implements ListsSearchInterface, ListsExcelInterface {

    protected $export_name = '导出';
    protected $export_lists = [];
    protected $export_fields = [];

    /**
     * @notes 设置搜索条件
     */
    public function setSearch(): array {
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        $year = mb_substr($search_month, 0, 4);
        $month = mb_substr($search_month, 4, 2);

        $m_arr = [];
        $m_arr['01'] = [$year . '01', $year . '02', $year . '03'];
        $m_arr['02'] = [$year . '01', $year . '02', $year . '03'];
        $m_arr['03'] = [$year . '01', $year . '02', $year . '03'];
        $m_arr['04'] = [$year . '04', $year . '05', $year . '06'];
        $m_arr['05'] = [$year . '04', $year . '05', $year . '06'];
        $m_arr['06'] = [$year . '04', $year . '05', $year . '06'];
        $m_arr['07'] = [$year . '07', $year . '08', $year . '09'];
        $m_arr['08'] = [$year . '07', $year . '08', $year . '09'];
        $m_arr['09'] = [$year . '07', $year . '08', $year . '09'];
        $m_arr['10'] = [$year . '10', $year . '11', $year . '12'];
        $m_arr['11'] = [$year . '10', $year . '11', $year . '12'];
        $m_arr['12'] = [$year . '10', $year . '11', $year . '12'];

        $where = $where_log = [];
        if ($search_month == date("Ym")) {
//            $where[] = ["log_date", "in", $m_arr[$month]];
        }
        $where_log[] = ["log_date", "in", $m_arr[$month]];

        $param = $this->request->param();

        if (!empty($this->adminCid) && $this->adminCid !== 0) {
            $where[] = ['cid', '=', $this->adminCid];
        }
        if (!empty($param['cb_ids'])) {
            if (!empty($param['cb_ids'][0])) {
                $where[] = ['cid', '=', $param['cb_ids'][0]];
                $where_log[] = ['cid', '=', $param['cb_ids'][0]];
            }
            if (!empty($param['cb_ids'][1])) {
                $where[] = ['bid', '=', $param['cb_ids'][1]];
                $where_log[] = ['bid', '=', $param['cb_ids'][1]];
            }
        }

        if (isset($param['room_keyword']) && $param['room_keyword'] != '') {
            $where[] = ['name|address', 'like', '%' . $param['room_keyword'] . '%'];
            $where_log[] = ['name|address', 'like', '%' . $param['room_keyword'] . '%'];
        }

        if (isset($param['user_keyword']) && $param['user_keyword'] != '') {
            $where[] = ['user_name|user_mobile', 'like', '%' . $param['user_keyword'] . '%'];
            $where_log[] = ['user_name|user_mobile', 'like', '%' . $param['user_keyword'] . '%'];
        }

        if (isset($param['room_type']) && $param['room_type'] != "") {
            $where[] = ["type", "=", $param['room_type']];
            $where_log[] = ["type", "=", $param['room_type']];
        }

        return [
            "where" => $where,
            "where_log" => $where_log,
        ];
    }

    /**
     * @notes 获取科室用户关联列表
     */
    public function lists(): array {
//        $ids = RoomHospital::where($this->setSearch())->select()->toArray();
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");
        $year = mb_substr($search_month, 0, 4);
        $month = mb_substr($search_month, 4, 2);
        if ($month % 3 == 1) {
            $season_month = [$month * 1, $month * 1 + 1, $month * 1 + 2];
        } elseif ($month % 3 == 2) {
            $season_month = [$month * 1 - 1, $month * 1, $month * 1 + 1];
        } else {
            $season_month = [$month * 1 - 2, $month * 1 - 1, $month * 1];
        }
        $log_data_text = $year . '年'
            . str_pad($season_month[0], 2, '0', STR_PAD_LEFT)
            . '+' . str_pad($season_month[1], 2, '0', STR_PAD_LEFT)
            . '+' . str_pad($season_month[2], 2, '0', STR_PAD_LEFT)
            . '月';

        $data = [
            "db" => new \think\Db(),
        ];
        $union = [];

        if ($search_month == date("Ym")) {
            $union[] = RoomHospital::field([
                "id as rid", "name as room_name", "'" . $search_month . "' as log_date", "sort",
                "room_department", "room_department_sort",
                "user_id", "user_name", "user_mobile",
                "lift_fee as room_lift_fee", "second_pressure_fee as room_second_pressure_fee",
//                "room_s_use_total", "room_s_price", "room_s_total_fee",
//                "room_d_use_total", "room_d_price", "room_d_total_fee",
//                "room_all_total_fee",
            ])->where($this->setSearch()['where'])
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_s_use_total';
                    $query->where('device_type', 1);
                }], "use_total")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_s_price';
                    $query->where('device_type', 1);
                }], "price")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_s_total_fee';
                    $query->where('device_type', 1);
                }], "total_fee")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_d_use_total';
                    $query->where('device_type', 2);
                }], "use_total")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_d_price';
                    $query->where('device_type', 2);
                }], "price")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_d_total_fee';
                    $query->where('device_type', 2);
                }], "total_fee")
                ->withSum(["allDevice" => function ($query, &$alias) {
                    $alias = 'room_all_total_fee';
                }], "total_fee")
                ->buildSql();
//                ->select()->toArray();
        }
//        var_dump($union);exit;

        $query = RoomHospitalLog::field([
            "rid", "name as room_name", "log_date", "sort",
            "room_department", "room_department_sort",
            "user_id", "user_name", "user_mobile",
            "room_lift_fee", "room_second_pressure_fee",
            "room_s_use_total", "room_s_price", "room_s_total_fee",
            "room_d_use_total", "room_d_price", "room_d_total_fee",
            "room_all_total_fee",
        ])->where($this->setSearch()['where_log'])->group("rid");
        if (count($union) > 0) {
            $query->union($union);
        }
        $result = $query->order([
            $data['db']->raw("field(room_department_sort, '*') asc"), // 科室排序 * 在最后
            $data['db']->raw('convert(room_department_sort using gbk) asc'), // 先进行科室排序
            "sort asc", // 楼栋排序
        ])->select()->toArray();

        $export_lists = [];
        $export_value = [
            "name" => null, "room_department" => '空', "room_department_sort" => '',
            "room_s_use_total" => 0, "room_s_price" => 0, "room_s_total_fee" => 0,
            "room_d_use_total" => 0, "room_d_price" => 0, "room_d_total_fee" => 0,
            "room_lift_fee" => 0, "room_second_pressure_fee" => 0, "room_all_total_fee" => 0,
        ];

        foreach ($result as $k => &$v) {
            $v['room_all_total_fee'] = 1 * sprintf("%.2f", $v['room_all_total_fee']);

            $export_key = $v['rid'] . '-' . $v['user_name'] . '-' . $v['user_mobile'];
            if (empty($export_lists[$export_key])) {
                $export_lists[$export_key] = $export_value;
            }

            $export_lists[$export_key] = [
                "log_date" => $log_data_text,
                "room_name" => $v['room_name'],
                "user_name" => $v['user_name'],
                "rid" => $v['rid'],
                "room_department" => $export_lists[$export_key]['room_department'] == '空' ? (empty($v['room_department']) ? '空' : $v['room_department']) : '空',

                "room_s_use_total" => DataHandleService::array_add([
                    $export_lists[$export_key]['room_s_use_total'], $v['room_s_use_total']
                ], 2),
                "room_s_price" => DataHandleService::array_average([
                    $export_lists[$export_key]['room_s_price'], $v['room_s_price']
                ], 6),
                "room_s_total_fee" => DataHandleService::array_add([
                    $export_lists[$export_key]['room_s_total_fee'], $v['room_s_total_fee']
                ], 2),

                "room_d_use_total" => DataHandleService::array_add([
                    $export_lists[$export_key]['room_d_use_total'], $v['room_d_use_total']
                ], 2),
                "room_d_price" => DataHandleService::array_average([
                    $export_lists[$export_key]['room_d_price'], $v['room_d_price']
                ], 6),
                "room_d_total_fee" => DataHandleService::array_add([
                    $export_lists[$export_key]['room_d_total_fee'], $v['room_d_total_fee']
                ], 2),

                "room_lift_fee" => DataHandleService::array_add([
                    $export_lists[$export_key]['room_lift_fee'], $v['room_lift_fee']
                ], 2),
                "room_second_pressure_fee" => DataHandleService::array_add([
                    $export_lists[$export_key]['room_second_pressure_fee'], $v['room_second_pressure_fee']
                ], 2),
                "room_all_total_fee" => DataHandleService::array_add([
                    $export_lists[$export_key]['room_all_total_fee'], $v['room_all_total_fee']
                ], 2),
            ];
        }

        $export_lists = array_values($export_lists);
        return $export_lists;
    }

    /**
     * @notes 获取科室用户关联数量
     */
    public function count(): int {
        return 100;
    }


    public function setExport($name, $lists, $fields) {
        $this->export_name = $name;
        $this->export_lists = $lists;
        $this->export_fields = $fields;
    }


    public function setFileName(): string {
        $search_month = $this->request->param("search_month") > 0 ? $this->request->param("search_month") : date("Ym");

        $year = mb_substr($search_month, 0, 4);
        $month = mb_substr($search_month, 4, 2);

        $m_arr = [];
        $m_arr['01'] = "01-02-03月";
        $m_arr['02'] = "01-02-03月";
        $m_arr['03'] = "01-02-03月";
        $m_arr['04'] = "04-05-06月";
        $m_arr['05'] = "04-05-06月";
        $m_arr['06'] = "04-05-06月";
        $m_arr['07'] = "07-08-09月";
        $m_arr['08'] = "07-08-09月";
        $m_arr['09'] = "07-08-09月";
        $m_arr['10'] = "10-11-12月";
        $m_arr['11'] = "10-11-12月";
        $m_arr['12'] = "10-11-12月";

        return '全院住户信息表-' . $year . '年' . $m_arr[$month];
    }

    public function setExcelLists() {
        return null;
    }

    /**
     * @notes 导出字段
     * @return string[]
     * @author 段誉
     * @date 2022/11/24 16:17
     */
    public function setExcelFields(): array {
        return [
            'room_name' => '房间信息',
            'user_name' => '住户信息',
            'room_department' => '科室',
            'room_d_use_total' => '用电度数',
            'room_d_price' => '电单价',
            'room_d_total_fee' => '总电费',
            'room_s_use_total' => '用水度数',
            'room_s_price' => '水单价',
            'room_s_total_fee' => '总水费',
            'room_lift_fee' => '电梯费',
            'room_second_pressure_fee' => '二次加压费',
            'room_all_total_fee' => '总费用',
            'log_date' => '时间',
        ];
    }

}
